import os
import platform
from SCons.Script import *
import config


deps = ['osx']


def getLibVars(env, lib):
    if os.environ.has_key(lib + '_INCLUDE'):
        env.AppendUnique(CPPPATH =
                   os.environ[lib + '_INCLUDE'].split(os.pathsep))

    if os.environ.has_key(lib + '_LIBPATH'):
        env.AppendUnique(LIBPATH =
                   os.environ[lib + '_LIBPATH'].split(os.pathsep))

    if os.environ.has_key(lib + '_LINKFLAGS'):
        env.AppendUnique(LINKFLAGS = [os.environ[lib + '_LINKFLAGS'].split()])


def configure(conf):
    env = conf.env

    for lib in ['GLEW', 'GLUT', 'GL']: getLibVars(env, lib)

    glewlib = 'GLEW'

    if env['PLATFORM'] == 'darwin':
        config.configure('osx', conf)

        if not (conf.CheckOSXFramework('OpenGL') and
                conf.CheckCHeader('OpenGL/gl.h')):
            raise Exception, 'Need OpenGL'

        if not (conf.CheckOSXFramework('GLUT') and
                conf.CheckCHeader('GLUT/glut.h')):
            raise Exception, 'Need GLUT'

    else:
        if env['PLATFORM'] == 'win32':
            glewlib = 'glew32s' # The static version
            freeglutlib = 'freeglut_static'
            glutlib = 'glut32'
            glulib = 'glu32'
            gllib = 'opengl32'

            env.AppendUnique(CPPDEFINES =
                       ['GLEW_BUILD=GLEW_STATIC', 'FREEGLUT_STATIC'])

        else:
            freeglutlib = glutlib = 'glut'
            glulib = 'GLU'
            gllib = 'GL'

        config.require_lib(conf, gllib)
        config.require_lib(conf, glulib)

        if not (conf.CheckCHeader('GL/glut.h') and \
                    (config.check_lib(conf, freeglutlib) or \
                         config.check_lib(conf, glutlib))):
            raise Exception, 'Need glut'

    if not (conf.CheckCHeader('GL/glew.h') and config.check_lib(conf, glewlib)):
        raise Exception, 'Need GLEW'

    return True
